package com.hzw.saas.service.ticket.service;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.hzw.saas.api.property.IPropertyService;
import com.hzw.saas.api.property.enmus.SysDictKeyEnum;
import com.hzw.saas.api.ticket.ITicketAccessService;
import com.hzw.saas.api.ticket.bo.TicketCreateUserBO;
import com.hzw.saas.api.ticket.response.TicketResponse;
import com.hzw.saas.api.user.ICustomerService;
import com.hzw.saas.api.user.bo.CustomerBO;
import com.hzw.saas.common.config.util.AssertUtil;
import com.hzw.saas.common.util.Json;
import com.hzw.saas.service.ticket.config.TicketConfig;
import com.hzw.saas.service.ticket.mode.Ticket;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * @author sonam
 * @sine 2021/10/20 10:56 上午
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TicketAccessServiceImpl implements ITicketAccessService {

    private final TicketServiceImpl ticketService;
    private final ICustomerService customerService;

    @Resource(name = IPropertyService.SYS_DICT_BEAN)
    private final IPropertyService<SysDictKeyEnum> propertyService;

    @Override
    @Transactional
    public TicketCreateUserBO access(String userId, String name, String phone, String email) {
        String propertyValue = propertyService.getPropertyValue(SysDictKeyEnum.TICKET_API);
        TicketConfig ticketConfig = Json.parseObject(propertyValue, TicketConfig.class);

        CustomerBO customer = customerService.getCustomerByUserId(userId);

        TicketResponse<Map<String, String>> access = this.access(ticketConfig);
        AssertUtil.assertThrow("接入工单服务失败", Objects.isNull(access));
        String token = access.getData().get("token");

        Ticket ticket = ticketService.lambdaQuery().eq(Ticket::getUserId, userId).one();
        TicketCreateUserBO ticketCreateUserBO = new TicketCreateUserBO();
        ticketCreateUserBO.setToken(token);

        if(Objects.isNull(ticket)) {
            Object apiCreateUser = ticketConfig.getApiCreateUser();
            String createUserResponseStr = HttpUtil.post(StrUtil.format("{}?token={}", apiCreateUser, token),
                MapUtil.builder(new HashMap<String, Object>())
                    .put("name", name)
                    .put("vip", Optional.ofNullable(customer).map(CustomerBO::getCustomerLevel).orElse("0"))
                    .put("phone", phone)
                    .put("email", email)
                    .map());
            log.info("{}: {}", apiCreateUser, createUserResponseStr);
            TicketResponse<Map<String, String>> ticketResponse = Json.parseObject(createUserResponseStr, TicketResponse.class);
            AssertUtil.assertThrow("接入工单服务失败，创建工单用户失败", Objects.isNull(ticketResponse) || !Objects.equals(ticketResponse.getCode(), 200));
            String userTicketId = ticketResponse.getData().get("id");
            ticketCreateUserBO.setUserTicketId(userTicketId);
            // 保存
            Ticket ticket1 = new Ticket();
            ticket1.setTicketUserId(userTicketId);
            ticket1.setUserId(userId);
            ticketService.save(ticket1);
        } else {
            ticketCreateUserBO.setUserTicketId(ticket.getTicketUserId());
            // 更新会员等级
            HttpUtil.post(StrUtil.format("{}?token={}", ticketConfig.getApiUpdateUser(), token),
                MapUtil.builder(new HashMap<String, Object>())
                    .put("name", name)
                    .put("vip", Optional.ofNullable(customer).map(CustomerBO::getCustomerLevel).orElse("0"))
                    .put("phone", phone)
                    .put("email", email)
                    .map());
        }

        return ticketCreateUserBO;
    }

    private TicketResponse<Map<String, String>> access(TicketConfig ticketConfig) {
        String getTokenResponseStr = HttpUtil.post(ticketConfig.getApiGetToken(), MapUtil.builder(new HashMap<String, Object>())
            .put("appid", ticketConfig.getAppId())
            .put("secret", ticketConfig.getSecret()).map());
        return Json.parseObject(getTokenResponseStr, TicketResponse.class);
    }

}
